﻿/*
 * User: Masy Freddy
 * Date: 09/02/2012
 * Time: 7:33 
 */
using System;
using System.AddIn.Hosting;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using MetaVideoEditorEvolved.AddIn.HostViews;
using MetaVideoEditorEvolved.Engine.Entity;

namespace MetaVideoEditorEvolved.Engine
{
	/// <summary>
	/// Description of AddInExtraToolsManager.
	/// </summary>
	public class AddInExtraToolsManager : AddInManager
	{
		private static AddInExtraToolsManager currentInstance;
		private static object syncRoot = new Object();
		private List<KeyValuePair<AddInInformation, ExtraToolsView>> extraToolsAddins = new List<KeyValuePair<AddInInformation, ExtraToolsView>>();
		
		public AddInExtraToolsManager()
		{
			Collection<AddInToken> extraToolsAddIns = AddInStore.FindAddIns(typeof(AddIn.HostViews.ExtraToolsView), addInPath);

			InsertAddIns(extraToolsAddIns, AddInType.ExtraTools);
			
			InitializeAddIn();
		}
		
		public static AddInExtraToolsManager Current
		{
			get
			{
				if(currentInstance == null)
				{
					lock (syncRoot)
					{
						currentInstance = new AddInExtraToolsManager();
					}
				}
				
				return currentInstance;
			}
		}
		
		public void InitializeAddIn()
		{
			extraToolsAddins.Clear();
			
			var addinOrder = from ai in AddIns
				orderby ai.Index
				select ai;
			
			foreach (var addin in addinOrder) {
				if(addin.IsEnable)
				{
					if(!(extraToolsAddins.Where((o) => o.Key == addin).Any()))
					{
						ExtraToolsView addInInstance = addin.Token.Activate<ExtraToolsView>(AddInSecurityLevel.FullTrust);
						extraToolsAddins.Add(new KeyValuePair<AddInInformation, ExtraToolsView>(addin, addInInstance));
					}
				}
			}
			
			AddIns = (from ai in AddIns
			          orderby ai.Index
			          select ai).ToList();
		}
		
		public override void SaveAllConfiguration()
		{
			base.SaveAllConfiguration();
			
			extraToolsAddins = new List<KeyValuePair<AddInInformation, ExtraToolsView>>();
			
			InitializeAddIn();
		}
		
		public void ShowOption(AddInInformation addInInformation)
		{
			AddInProcess addInProcess = new AddInProcess();
			addInProcess.Start();

			ExtraToolsView addInInstance =  addInInformation.Token.Activate<ExtraToolsView>(addInProcess, AddInSecurityLevel.FullTrust);
			
			addInInstance.ShowOption();
			
			addInProcess.Shutdown();
		}
		
		
		public bool HasOption(AddInInformation addInInformation)
		{
			ExtraToolsView addInInstance = null;
			
			var addin = extraToolsAddins.Where((o) => o.Key == addInInformation);
			
			if(addin.Any())
			{
				addInInstance = addin.First().Value;
			}
			else
			{
				addInInstance = addInInformation.Token.Activate<ExtraToolsView>(AddInSecurityLevel.FullTrust);
			}
			
			return addInInstance.HasOption();
		}
	}
}
